<template>
  <div class="search-container">
    <!-- 1.0导航栏 -->
    <van-nav-bar
      left-arrow
      @click-left="$router.go(-1)"
      title="搜索中心"
    ></van-nav-bar>
    <!-- 2.0 搜索框-->
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="
        $router.push({ path: '/searchRuslt', query: { keywords: value } })
      "
      @input="onInput"
    >
      <template #action>
        <div
          @click="
            $router.push({ path: '/searchRuslt', query: { keywords: value } })
          "
        >
          搜索
        </div>
      </template>
    </van-search>
    <!-- 3.0搜索联想 -->
    <van-cell
      v-for="(item, index) in showList"
      :key="index"
      icon="search"
      @click="
        $router.push({
          path: '/searchRuslt',
          query: { keywords: options[index] },
        })
      "
    >
      <template #title>
        <div v-html="item"></div>
      </template>
    </van-cell>
    <!-- 4.0历史记录 -->
    <van-cell title="历史记录" />
    <van-cell v-for="item in history" :key="item" :title="item">
      <template #right-icon>
        <van-icon name="close" class="search-icon" @click="delClick" />
      </template>
    </van-cell>
  </div>
</template>

<script>
// 导入axions  搜索历史  删除历史
import { getSuggestion, searchHistory, delHistories } from "./home.js";
export default {
  name: "search",
  data() {
    return {
      value: "", //用户实时输入的内容
      options: [], //联想匹配的内容
      history: [], //历史记录
      timeID: null,
    };
  },
  async created() {
    let res = await searchHistory();
    // console.log(res);
    // 绑定数据
    this.history = res.data.data.keywords;
  },
  methods: {
    // 删除历史记录
    async delClick(item) {
      //  发起请求
      let res = await delHistories({ message: item });
      console.log(res);
      if (res.status == 204) {
        this.$toast.success("删除成功");
        this.history = [];
      } else {
        this.$toast.success("删除失败");
      }
    },
    onInput() {
      clearTimeout(this.timeID);
      this.timeID = setTimeout(async () => {
        // 非空判断
        if (this.value == "") {
          this.options = [];
          return;
        }
        let res = await getSuggestion({ q: this.value });
        // console.log(res);
        // 绑定数据
        this.options = res.data.data.options;
      }, 500);
    },
  },
  computed: {
    showList() {
      // 创建正则 new一个RegExp对象
      let reg = new RegExp(this.value, "ig");
      // map  映射一个新数组用于显示
      return this.options.map((value) =>
        value.replace(reg, (match) => {
          `<span style="color:red">${match} </span>`;
        })
      );
    },
  },
};
</script>

<style lang ="less">
</style>